﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;

namespace Ivory
{
    /// <summary>
    /// A basic loading screen with Text only
    /// </summary>
    public sealed class LoadScreen : LoadScreenBase
    {
        //Fields 
        private SpriteFont screenFont;
        private Texture2D backgroundImg;
        private Color backgroundColor, textColor;
        private TimeSpan elapsedTime = TimeSpan.FromSeconds(0);
        private string fontholder;

        public string LoadingText = "Loading (NaN) ...";

        //Construct
        public LoadScreen(Game game, string font, Color txtColor, Color backgroundColor)
            : base(game)
        {
            if (!string.IsNullOrEmpty(font))                
                fontholder = font;
            else
                fontholder = null;

            this.backgroundColor = backgroundColor;
            this.textColor = txtColor;
        }

        //Methods
        public override void RenderLoadScreen(SpriteBatch batch, GameTime time)
        {
            batch.Begin();
            
            //1/ Draw the background Img 
            batch.Draw(backgroundImg, Manager.WindowRect, Color.White);
            
            //2/ Draw the text in center of the screen 
            Vector2 Point = new Vector2(Manager.WindowRect.Center.X, Manager.WindowRect.Center.Y) - screenFont.MeasureString(LoadingText);

            batch.DrawString(screenFont, LoadingText, Point, textColor);

            batch.End();
        }

        public override void UpdateLoadScreen(GameTime time)
        {
            elapsedTime += time.ElapsedGameTime;

            LoadingText = "Loading (" + LoadingTime.Seconds.ToString() +")";

            if (elapsedTime > TimeSpan.FromSeconds(2)) {
                elapsedTime = TimeSpan.FromSeconds(0);
                LoadingText += " ...";
            }
            else if (elapsedTime > TimeSpan.FromSeconds(1))
                LoadingText += " ..";
            else
                LoadingText += " .";
        }

        public override void LoadAssets(ContentManager content)
        {
            if (fontholder != null)
                screenFont = content.Load<SpriteFont>(fontholder);
            
            backgroundImg = Ivory.Libs.TextureBuilder.CreateTexture(Game.GraphicsDevice,
                Manager.WindowRect.Width, Manager.WindowRect.Height, backgroundColor); 
        }
    }
}
